// 车险表单数据仓库
import Vue from 'vue'
import router from '@/router/index'
import * as components from '@/components/ivew_conf/car_form_mod_conf'
import CarModel from '@/components/ivew_conf/car_model' 
import carStatusConf from '@/components/ivew_conf/car_status_conf'
import loop from '@/utils/loop'
import {deepCopy} from '@/utils/tools'
import CarDanger from '@/components/ivew_conf/car_danger'
import CarNewOrderTemplate from '@/components/ivew_conf/car_new_order_template'
import carUploadMods from '@/components/ivew_conf/car_upload_mods'
import { carIndiaOrderInfo } from '@/components/ivew_conf/car_india_single'
import {template as singleTemplate} from '@/components/ivew_components/car_india/dataTemplate' 
import {filter as carFormToolsFilter} from '@/components/form_tools/status_filter'
import { updateCarTable } from '../../components/table_tools';
import StatusBox from '@/components/ivew_conf/state_store'
import powerFilter from '@/components/ivew_conf/power/power_filter'

const carStatusBox = new StatusBox()

// 车险出险率,数据映射管理
let dangerTypeMap = {
    
    syMap:{
        'sySupplier': 'company',
        'syChuXianGaiShu': 'chuXianGaiShu',
        'syChuXianCiShu': 'chuXianCiShu',
    },
    
    jqMap:{
        'jqSupplier': 'company',
        'jqChuXianGaiShu': 'chuXianGaiShu',
        'jqChuXianCiShu': 'chuXianCiShu',
    }
};

// 车险明细,数据映射(获取数据地址, index为自定义标识)
let detailedMap = {
    
    vin: 'DEVvin',
    price: 'DEVprice',

    brand: 'brand',
    vehicleName: 'vehicleName',
    weight: 'weight',
    seats:'seats',
    releaseYear: 'releaseYear',
    engineCapability: 'engineCapability',
    tonnages: 'tonnages',
    energyType: 'energyType',
    vehicleId: 'vehicleId',

    index:'index',

}

interface componentStore{
    [propname:string]:any
}

interface initParams{
    orderId:string,
    orderStatus:string,
}

class stateInf {

    formMod:string
    orderStatus:string
    orderId:string    
    componentStore:formInf.mod[]
    orderSource:internalInf.carOrderAPI | {}
    orderData:internalInf.carOrderAPI | {}
    carModules: carModel[]
    currentCarModel: carModel | {}
    dangerPropbability:carDanger | {}
    chargingData: any[] | undefined
    carUploadList: any[]
    indiaOrderInfo: formInf.indiaOrderInfo
    indiaSingle:{[propname:string]:formInf.indiaSingle}
    currentSingleType:string
    chargingCode:formInf.chargingCode | undefined
    currentSingleGetType: 'JQ' |'SY'
    usableSingle: {
        JQ: formInf.singleList
        SY: formInf.singleList
    }

    carStatusConf: stateConf[]
    
}


export default class carFormStore {


    state:stateInf = {

        // 表单显示模式
        formMod: 'all',
        
        // 订单状态
        orderStatus: '',

        // 订单Id
        orderId: '',

        // 表单加载模块
        componentStore: components.formEdit,

        //元数据备份
        orderSource: {},
        
        // 表单数据挂载对象
        orderData: new CarNewOrderTemplate(),

        // 车型信息
        carModules:[],

        // 当前选中车型
        currentCarModel: {},

        // 出险率
        dangerPropbability: new CarDanger({}),

        // 计费数据
        chargingData: [],
        
        // 计费二维码
        chargingCode: undefined,
        
        // 附件列表
        carUploadList: deepCopy(carUploadMods),
        
        // 集印订单基础信息
        indiaOrderInfo: new carIndiaOrderInfo(),
        
        // 集印单证列表
        indiaSingle: deepCopy(singleTemplate),

        // 当前操作单证
        currentSingleType: '',
        

        // 可用单证
        usableSingle: {
            JQ: {
                policys: [],
                baoKa: [],
                invoices: []
            },

            SY: {
                policys: [],
                baoKa: [],
                invoices: []
            }
        },
      
        // 当前请求可用单证类型
        currentSingleGetType: 'JQ',
 
        // 车险表单配置( 供权限使用 )
        carStatusConf: carStatusConf
    }

    mutations = {

        // 设置车险表单配置
        setCarStatusConf(state, data){

            state['carStatusConf'] = data;
            
        },

        update (state, {target, data}){

            if(state.hasOwnProperty(target)){
                state[target] = data;
            }else{
                throw `表单数据更新错误：${target}不存在`
            }
        },

        
        // 修改当前操作单证状态 
        changeCurrentSingleGetType(state, type:'JQ' | "SY"){
            state.currentSingleGetType = type;
        },

        // 分发请求可用单证
        issueUsableSingle(state, data:formInf.singleList){
            state.usableSingle[state.currentSingleGetType] = data;
        },

        // 更新单证号 （配置分发方法时， 调用那个当前操作订单值得方法 应在清除 "操作订单类型方法" 之前）
        updateSingleNumber(state, data){
            Object.assign(data, {status: '分配集印'});
            Object.assign(state.indiaSingle[state.currentSingleType], data);
        },

        // 删除单证
        deleteSingleNumber(state){
            state.indiaSingle[state.currentSingleType]['status'] = '待分配';
            state.indiaSingle[state.currentSingleType]['serialNumber'] = '';
        },
        
        // 修改已集印缓存状态
        toIndiaSingleNumber(state){
            state.indiaSingle[state.currentSingleType]['status'] = '已集印';
        },

        // 打单成功,修改单证状态
        toIntimidateSingleNumber(state){
            state.indiaSingle[state.currentSingleType]['status'] = '已打单';
        },
        
        // 清除单证状态
        clearCurrentSingleType(state){
            state.currentSingleType = '';
        },
        
        // 计费二维码
        updateChargingCode (state, data){
            state.chargingCode = data
        },
        
        // 单证列表
        updateIndiaSingle(state, data){
            state.indiaSingle = data
        },

        // 集印 打单 订单信息
        updateIndiaOrderInfo (state, data){
            state.indiaOrderInfo = data
        },
        
        // 为新建订单添加订单号
        pushNewOrderId(state, orderId:string){
            state.orderData['Did'] = orderId;            
        },

        // 更新附件列表 (返回为空数组时，配置默认值)
        updateCarUploadList (state, data){
            state.carUploadList = data;
        },

        // 订单数据(只用在数据分配)
        allotReqOrderData (state, data:internalInf.carOrderAPI){
            state.orderData = data;
            state.orderSource = deepCopy(data);
        },
        
        // 更新车型数据
        updateCarModels (state, data:carModel[]){
            state.carModules = data;
        },

        // 更新当前车型选中项, 同时更新订单数据
        updateCurrentCarModel (state, currentData:carModel){

            let orderData = state.orderData;
            let map = {
                'price': 'DEVprice',
                'seats': 'DEVseats',
                'engineCapability' :'DEVengineCapacity',
                'tonnages': 'DEVtonnages',
                'weight': 'DEVweight',
                'vehicleId': 'DEVvehicleId',
                'energyType': 'DEVenergyType',
                'model': 'DEVmodel',
            }
            
            // 更新订单数据
            let end = loop.assignment(deepCopy(currentData), orderData, map, true);

            state.currentCarModel = currentData;
        },

        // 更新计费数据
        updateDquotations (state, data){
            state.chargingData = data;
        },

        // 更新出险率
        updateDanger (state, data){
            state.dangerPropbability = data;
        },

        /*
        ** 更新手工填入数据 (出险率)
        ** params: 
            tableData: 出险率表格数据
            auxilinary: 车船税，纯风险保费
        */
        completionDangerData(state, {tableData, auxiliary}){
            let dangerPropbability = state.dangerPropbability;
            let map = {
                sy: {},
                jq: {}
            };

            tableData.forEach(item =>{

                // item.key  'sy' | 'jq'
                let sourceMap = dangerTypeMap[item.key + 'Map']
                
                Object.keys(sourceMap).forEach(key =>{
                    map[item.key][sourceMap[key]] = key;
                    
                })

                loop.assignment(item, dangerPropbability, map[item.key], true)
                
            })

            Object.assign(state.dangerPropbability, auxiliary)

        },
        
        // 更新手工填入数据 (车型信息)
        completionDetailed(state, data){
            
            Object.keys(detailedMap).forEach(key =>{

                let propname = detailedMap[key];
                let val = data[key]
                
                if(state.orderData.hasOwnProperty(propname)){
                    
                    // 为空时不进行替换
                    if(val || val === 0){
                        state.orderData[propname] = data[key];
                    }
                    
                }else{

                    // 修改车型列表内对应条目数据 （如果缓存在当前选中项，再次选择后，数据将丢失）
                    state.carModules[state.currentCarModel.index][propname] = data[key];
                    
                }
                
            })

            // 保证当前选中显示
            state.carModules[state.currentCarModel.index]['_highlight'] = true;

            // 注:需要补全 index 标记
            state.currentCarModel = deepCopy(state.carModules[state.currentCarModel.index])
        }
        
    }

    getters = {
         
        // 当前表单加载组件
        currentComponentStore (state){
            let currentStatusConf = carStatusBox.getVal(state['orderData']['Sstatus'])            
            return components[currentStatusConf['component']];
        },  

        // 动态车险表单操作按键
        controlBtns(state){
            let orderStatus = state.orderData.Sstatus; 
            return carFormToolsFilter(orderStatus, state.carStatusConf)
        },
        
        // 当前可用单证
        currentUsableSingle (state){
            return state['usableSingle'][state['currentSingleGetType']]
        },

        // 判断订单数据是否改变
        orderDataHasChange(state):boolean {
            return JSON.stringify(state.orderData) === JSON.stringify(state.orderSource)
        },
        
        // 出险率辅助信息（车船税， 纯风险保费）
        carDangerAuxiliary(state):formInf.carDangerAuxiliary{  
            let vehicleTax = state.dangerPropbability.vehicleTax || 0;
            let pureRiskPremiums = state.dangerPropbability.pureRiskPremiums || 0;

            return {vehicleTax, pureRiskPremiums}
        },

        // 出险率表格数据
        carDangerTableData(state){

            let dangerPropbability = state.dangerPropbability;

            let syDanger = {
                label: '商业险',
                key: 'sy',
            };

            let jqDanger = {
                label: '交强险',
                key: 'jq',
            }
            
            // 取值
            loop.assignment(dangerPropbability, syDanger, dangerTypeMap.syMap)
            loop.assignment(dangerPropbability, jqDanger, dangerTypeMap.jqMap)

            return [syDanger, jqDanger]

        },


        // 当前选中车型明细
        currentDetailed(state):formInf.carDetailedTableItem | {}{
            let currentCarModel = state.currentCarModel;
            let orderData= state.orderData;
            let detailed = {}
            
            Object.keys(detailedMap).forEach(key =>{
                let propsname = detailedMap[key]
                detailed[key] = orderData[propsname] !== undefined ? orderData[propsname] : currentCarModel[propsname];
            })

            return detailed
        },
        

        // 过滤商业险数据(只展示计费时已配置项数据)
        syChargingHasKeys(state){
            let syRiskTable = state.orderSource.DEVsyRiskTable;
            let hasKey = {};

            if(syRiskTable){

                syRiskTable.forEach(item =>{
                    
                    if(item.checked){
                        hasKey[item.key] = true;
                    }
                    
                })
                
            }

            // 免赔特例,无该关键字
            hasKey['mianPei'] = true;
            
            return hasKey
        },

        // 主显示计费投保公司
        chargingSelectedCompany (state){

            let { DEVjqViCompany: jqCompany,  DEVsyViCompany: syCompany} = state.orderSource;
            
            return {
                jqCompany,
                syCompany,
            }
        }
        
    }

    actions = {

        // 更新订单会员信息
        updateMemberInfo({state, commit, dispatch}){
            let currentMemberData = this['state']['organizationStore']['currentLoadFormData']
            let orderData = state['orderData']
            let map = {
                DMnickname: 'nickname',
                DMphone : 'phone',
                DMcompany: 'company',
                DMdepartment: 'department',
                DMlevel: 'level'
            }

            Object.keys(map).forEach(key  =>{
                orderData[key] = currentMemberData[map[key]];
            })

        },
        
        
        // 表单初始化
        initStore(context, params?:initParams){
            
            if(params){

                Object.keys(params).forEach(key =>{

                    context.commit({
                        type:'update',
                        target: key,
                        data: params[key]
                    })
                    
                })

                // 请求订单数据
                context.dispatch('request', {
                    url: 'get/orders/id',
                    data: {
                        orderId: params.orderId
                    }

                }, {root:true} )
                
                // 请求订单附件
                context.dispatch('request', {
                    url: 'get/files',
                    data: {
                        orderId: params.orderId
                    }
                }, {root:true})


                // 添加路径参数
                router.replace({
                    query: {
                        ...params
                    }
                })
                
                                
            }else{
                
                // 新建订单

                // 拼接初始数据
                let userBase = this.state['mainStore']['userBase']
                let orderTemplate = new CarNewOrderTemplate()
                Object.assign(orderTemplate, {
                    DMnickname: userBase.nickname,
                    DMphone: userBase.phone,
                    DMdepartment: userBase.department,
                    DMcompany: userBase.company,
                    DMlevel: userBase.extensions.member.level,
                })
                
                context.commit('update', {
                    target: 'orderData',
                    data: orderTemplate
                })

                // 初始化附件列表
                context.commit('updateCarUploadList', deepCopy(carUploadMods))
                

            }

            // 清空车型数据
            context.commit('updateCarModels', []);
            
            // 清除单证数据
            context.commit('updateIndiaSingle', deepCopy(singleTemplate))
           
        }

    }
    
}